package com.car.service.service.impl;

import com.car.service.entity.ChatSession;
import com.car.service.mapper.ChatSessionMapper;
import com.car.service.service.ChatSessionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 聊天会话服务实现类
 */
@Service
public class ChatSessionServiceImpl implements ChatSessionService {
    
    @Autowired
    private ChatSessionMapper chatSessionMapper;
    
    @Override
    @Transactional
    public ChatSession createSession(Long userId, Long serviceId) {
        // 检查是否已存在会话
        ChatSession existingSession = chatSessionMapper.selectByUserIdAndServiceId(userId, serviceId);
        if (existingSession != null) {
            return existingSession;
        }
        
        // 创建新会话
        ChatSession session = new ChatSession();
        session.setId(generateSessionId());
        session.setUserId(userId);
        session.setServiceId(serviceId);
        session.setStatus(1); // 进行中
        session.setUnreadCount(0);
        
        Date now = new Date();
        session.setCreateTime(now);
        session.setUpdateTime(now);
        
        chatSessionMapper.insert(session);
        return session;
    }
    
    @Override
    public ChatSession getSession(String sessionId) {
        return chatSessionMapper.selectById(sessionId);
    }
    
    @Override
    public List<ChatSession> getUserSessions(Long userId, int page, int size) {
        int offset = (page - 1) * size;
        return chatSessionMapper.selectByUserId(userId, offset, size);
    }
    
    @Override
    public List<ChatSession> getServiceSessions(Long serviceId, int page, int size) {
        int offset = (page - 1) * size;
        return chatSessionMapper.selectByServiceId(serviceId, offset, size);
    }
    
    @Override
    @Transactional
    public ChatSession updateSession(ChatSession session) {
        session.setUpdateTime(new Date());
        chatSessionMapper.update(session);
        return session;
    }
    
    @Override
    @Transactional
    public void closeSession(String sessionId) {
        ChatSession session = chatSessionMapper.selectById(sessionId);
        if (session != null) {
            session.setStatus(0); // 关闭
            session.setUpdateTime(new Date());
            chatSessionMapper.update(session);
        }
    }
    
    @Override
    @Transactional
    public void deleteSession(String sessionId) {
        chatSessionMapper.delete(sessionId);
    }
    
    /**
     * 生成会话ID
     */
    private String generateSessionId() {
        return UUID.randomUUID().toString().replace("-", "");
    }
} 